<template>
    <div>
        <el-descriptions :column="4" border class="margin-top" title>
            <el-descriptions-item>
                <template slot="label">用户登录时间</template>
                {{ userinfo.login_at }}
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">实名认证</template>
                <div class>
                    <el-tag :type="authenticationState == 1 ? 'success' : 'warning'" @click="visibleFun" class="text-center"
                        style="cursor: pointer;">
                        {{ authenticationState == 1 ? '已实名认证'
                            :
                            '未实名认证'
                        }}
                    </el-tag>
                </div>
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">真实姓名</template>
                {{ userinfo.cert_name }}
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">账户余额</template>
                {{ userinfo.balance }}
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">昵称</template>
                {{ userinfo.nickname }}
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">用户名</template>
                {{ userinfo.username }}
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">手机号</template>
                {{ userinfo.mobile }}
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">代理余额</template>
                {{ userinfo.agent_balance }}
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">下载2FAS</template>
                <div class>
                    <el-tag type="primary" @click="showDownloadFun" class="text-center" style="cursor: pointer;">
                        点击下载2FAS
                    </el-tag>
                </div>
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">是否绑定2FAS</template>
                <div class>
                    <el-tag :type="userinfo.has_twofas_key   || TwoFASBinding ? 'success' : 'warning'"
                        @click="TwoFASFun(userinfo.has_twofas_key)" class="text-center" style="cursor: pointer;">
                        {{ userinfo.has_twofas_key || TwoFASBinding ?
                            '已绑定' : '未绑定' }}
                    </el-tag>
                </div>
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">我的分享码</template>
                <div class>
                    <el-tag type="primary" @click="shareShow = true" class="text-center" style="cursor: pointer;">
                        查看我的分享码(分享二维码，邀请下级用户)
                    </el-tag>
                </div>
            </el-descriptions-item>

        </el-descriptions>




        <el-descriptions :column="4" border class="margin-top" title style="margin-top: 20px;">
            <el-descriptions-item>
                <template slot="label"> 直播付费盈利比例</template>
                {{ userinfo.live_fee_rate }}%
            </el-descriptions-item>


            <el-descriptions-item>
                <template slot="label">收到礼物的回扣比例</template>
                {{ userinfo.live_gift_rate }} %
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">长视频收益比例</template>
                {{ userinfo.long_rate }}%
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">短视频收益比例</template>
                {{ userinfo.short_rate }}%
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">打赏收益比例</template>
                {{ userinfo.tipping_rate }}%
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">1V1密聊收益比例</template>
                {{ userinfo.one_by_one_rate }}%
            </el-descriptions-item>

            <el-descriptions-item>
                <template slot="label">同城空降收益比例</template>
                {{ userinfo.same_city_rate }}%
            </el-descriptions-item>
        </el-descriptions>

        
        <el-descriptions :column="4" border class="margin-top" title style="margin-top: 20px;">
            <el-descriptions-item>
                <template slot="label"> 代理系统管理员</template>
                {{ authentication.admin_contact }} 
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">代理协议须知</template>
                
                <el-tag type="primary" @click="authenticationStateShow = true" class="text-center" style="cursor: pointer;">
                        点击查看代理协议须知
                    </el-tag>
            </el-descriptions-item>
        </el-descriptions>

        <el-card class="mt-10" style="margin-top: 50px;">
            <div class="block">
                <span class="demonstration">月份</span>
                <el-date-picker @change="rebateFun" placeholder="选择月" type="month" v-model="rebateValue"
                    value-format="yyyy-M"></el-date-picker>
            </div>
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-card class="mt-10">
                        <div>
                            <h3>当月返佣走势</h3>
                            <div ref="chart" style="width:100%;height:376px"></div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card class="mt-10">
                        <div style="width:100%;height:415px;position: relative;">
                            <h3>下级代理地域分布</h3>

                            <div ref="userRecharge" style="width:100%;height:376px"></div>
                            <div v-if="!map_statis"
                                style="color: #999;position: absolute; top: 100px;margin-left: 45%;z-index: 999;">暂无数据</div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>

        <!-- 实名认证 -->
        <el-dialog :title="title" :visible.sync="visible" width="700px">
            <el-form :model="authenticationForm" label-width="80px" ref="authenticationForm" v-if="title == '实名认证'">
                <el-form-item label="姓名">
                    <el-input placeholder="请输入姓名" style="width:500px" v-model="authenticationForm.cert_name"></el-input>
                </el-form-item>

                <el-form-item label="身份证号">
                    <el-input placeholder="请输入用户名" style="width:500px" v-model="authenticationForm.cert_no"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button @click="getCertifyId" style="width: 470px;margin: 30px auto;" type="primary">提交</el-button>
                </el-form-item>
            </el-form>

            <div class="flexCCC jus-center" v-else>
                <vue-qrcode :options="{ width: 200 }" :value="value" style="margin:0 auto ;"></vue-qrcode>
                <div>
                    <el-button @click="authenticationSubmit" style="width: 470px;margin: 30px auto;"
                        type="primary">已完成实名认证</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 绑定2FAS -->
        <el-dialog :visible.sync="TwoFASShow" :title="showDownload ? '下载2FAS' : '绑定2FAS'" width="700px">
            <div class="flexCCC jus-center">
                <vue-qrcode :options="{ width: 150 }" :value="download_url" style="margin:0 auto ;"
                    v-if="showDownload"></vue-qrcode>
                <img :src="TwoFASShowUrl" style="margin:0 auto ; width: 150px;" v-else />
                <div>
                    <el-button @click="TwoFASShowWC" style="width: 470px;margin: 30px auto;" type="primary">已完成</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 显示分享码 -->
        <el-dialog :visible.sync="shareShow" title="我的分享码" width="700px">
            <div class="flexCCC jus-center">
                <vue-qrcode id="qrcode" :options="{ width: 150 }" :value="shareUrl" style="margin:0 auto ;"></vue-qrcode>
                <div>
                   右键点击保存下载
                </div>
            </div>
        </el-dialog>

          <!-- 代理用户须知 -->
          <el-dialog :visible.sync="authenticationStateShow" title="代理协议须知" width="700px">
            <div class="" v-html="authentication.agent_notice">
            
            </div>
        </el-dialog>
    </div>
</template>

<script>
import config from '../utils/config'
import { mapGetters } from 'vuex'
import { Base64 } from 'js-base64'
import VueQrcode from '@chenfengyuan/vue-qrcode'
export default {
    components: {
        VueQrcode,
    },
    data() {
        return {
            res: {},
            agentDatas: {},
            authenticationState: localStorage.getItem('authenticationState'),
            visible: false,
            TwoFASShow: false,
            TwoFASBinding: false,
            authenticationStateShow:false,
            title: '实名认证',
            value: '',
            TwoFASShowUrl: '',
            rebateValue: '',
            map_statis: false,
            shareShow: false,
            authentication:{},
            shareUrl: "",
            rebateForm: {
                date: '',
            },
            authenticationForm: {
                cert_no: '',
                cert_name: '',
                meta_info: '',
                //  certify_id: ""
            },

            authenticationForm2: {
                cert_no: '',
                cert_name: '',
                certify_id: '',
            },
            showDownload: false,
            download_url: "http://agent.peixiua.com/download/2fas-auth-4-7-0.apk",
        }
    },
    computed: {
        ...mapGetters(['sidebar', 'userinfo']),
    },
    mounted() {
        if (this.$route.query.visible) {
            this.visible = this.$route.query.visible
        }
        this.authenticationForm.meta_info = Base64.encode(JSON.stringify(window.getMetaInfo()))
        this.$nextTick(() => {
            //  this.drawChartWithOrder()
            // this.drawChartWithMealSale()
            this.getAuthenticationState()
            this.getAgentNotice()
            this.getDate()
        })

        this.shareUrl = 'http://ground.miazh.com/#/?type=register&parent_agent=' + this.userinfo.id


    },
    methods: {
        visibleFun() {
            if (this.authenticationState == 1) {
                this.$message.success('已完成实名认证')
                return
            }
            this.visible = true
        },

        rebateFun(e) {
            console.log('e', e)
            this.rebateForm.date = e
            this.getDate(e)
        },
        TwoFASFun(e) {
            if (e) {
                this.$message.success("已绑定2FAS");
                return
            }
            // this.getLoadTwofasKey()
            this.$confirm('点击后请务必打开2FAS扫码绑定二维码，关闭之后不再显示二维码，如需更改请联系管理员', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '点击下载2FAS',
                type: 'warning',
            }).then(() => {
                    this.getLoadTwofasKey()
                    console.log('getLoadTwofasKey')
                })
                .catch(action => {

                    if (action === 'cancel') {
                        this.showDownload = true
                        this.TwoFASShow = true
                    } else {
                        this.TwoFASShowWC()
                    }

                })
        },

        TwoFASShowWC() {
            this.TwoFASShow = false
            this.showDownload = false
        },

        SaveSharingCode(url) {
            const canvas = document.getElementById('qrcode');
            VueQrcode.toCanvas(canvas, 'https://example.com', function (error) {
    if (error) console.error(error);
    console.log('QR code generated!');
    const dataURL = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.href = dataURL;
    link.download = 'sharing_code.png';
    link.click();
  });

        },

        showDownloadFun() {
            this.showDownload = true
            this.TwoFASShow = true
        },
        getLoadTwofasKey() {
            let that = this
            this.$request.get('/auth/load_twofas_key').then((res) => {
                that.TwoFASShowUrl = res.file_stream
                that.TwoFASShow = true
                that.showDownload = false //关闭下载
                that.TwoFASBinding = true
            })
        },

        getAuthenticationState() {
            this.$request.get('/auth/verify_status').then((res) => {
                console.log('getAuthenticationState',res)
                this.visible = false
                //0是为验证码 1是验证
                localStorage.setItem('authenticationState', res.status)
                this.authenticationState = localStorage.getItem('authenticationState')
            })
        },

        getCertifyId() {
            // delete this.authenticationForm['certify_id']
            this.$request.get('/auth/authentication', this.authenticationForm).then((res) => {
                this.authenticationForm2.cert_name = this.authenticationForm.cert_name
                this.authenticationForm2.cert_no = this.authenticationForm.cert_no
                this.authenticationForm2.certify_id = res.certify_id
                this.value = res.certify_url
                this.title = '扫码认证'
            })
        },

        authenticationSubmit() {
            // delete this.authenticationForm['meta_info']
            this.$request.post('/auth/verify', this.authenticationForm2).then((res) => {
    
                // if (!res.data.hasOwnProperty('certifyUrl')) {
                //     this.$message.error('未获取到实名认证链接')
                //     return
                // }

                //this.$message.error('未获取到实名认证链接')
                this.getAuthenticationState()
            })
        },

        getDate(e) {
            console.log('this.rebateForm', this.rebateForm)
            this.$request.get('/agent_count', this.rebateForm).then((res) => {
                console.log('统计图', res)
                this.agentDatas = res

                let days
                if (!e) {
                    // 创建一个表示当前日期的Date对象
                    var currentDate = new Date()
                    // 获取当前月份
                    var currentMonth = currentDate.getMonth()

                    // 获取年份和月份
                    var year = currentDate.getFullYear()
                    var month = currentDate.getMonth() + 1 // 月份从0开始，所以需要加1

                    // 格式化为 "YYYY-MM" 格式
                    var formattedDate = year + '-' + month
                    days = this.getDaysInMonth(formattedDate)
                } else {
                    days = this.getDaysInMonth(e)
                }

                const chart = this.$refs.chart

                if (chart) {
                    const myChart = this.$echarts.init(chart)
                    const option = {
                        xAxis: {
                            type: 'category',
                            data: [],
                        },
                        yAxis: {
                            type: 'value',
                        },
                        series: [
                            {
                                data: [],
                                type: 'line',
                            },
                        ],
                    }
                    for (let i = 1; i <= days; i++) {
                        option.xAxis.data.push(i)
                    }
                    for (let i = 1; i <= days; i++) {
                        option.series[0].data.push(0)
                    }
                    let date

                    console.log('res.profits_balance_month', res.profits_balance_month)
                    for (let i = 0; i < res.profits_balance_month.length; i++) {
                        console.log(res.profits_balance_month[i].date)
                        //  date.push(parseInt(res.month_user_increase[i].date.substring(5,7)))
                        date = parseInt(res.profits_balance_month[i].date.substring(8))
                        console.log(res.profits_balance_month[i].count)
                        option.series[0].data[date] = res.profits_balance_month[i].total
                    }
                    myChart.setOption(option)
                }

                const userRecharge = this.$refs.userRecharge

                //判断如果没有数据就显示暂无数据
                if (res.map_statis.length == 0) {
                    this.map_statis = false
                } else {
                    this.map_statis = true
                }

                if (userRecharge) {
                    const myUserRecharge = this.$echarts.init(userRecharge)
                    const option = {
                        title: {
                            text: '下级代理地域分布统计图',
                            subtext: '',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left'
                        },
                        series: [
                            {
                                name: '数据统计',
                                type: 'pie',
                                radius: '50%',
                                data: [

                                ],
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]

                    }

                    for (let i = 0; i <= res.map_statis.length; i++) {
                        option.series[0].data.push(res.map_statis[i])
                    }
                    // let dateTwo
                    // for (let i = 0; i < res.withdraw_money_month.length; i++) {
                    //     console.log(res.withdraw_money_month[i].date)
                    //     //  date.push(parseInt(res.month_user_increase[i].date.substring(5,7)))
                    //     dateTwo = parseInt(res.withdraw_money_month[i].date.substring(8))
                    //     option.series[0].data[dateTwo] = res.withdraw_money_month[i].total
                    // }
                    myUserRecharge.setOption(option)
                }
            })
        },

        getDaysInMonth(month) {
            console.log('month', month)
            // 将传入的月份格式转换为 Date 对象的格式
            const [year, monthNumber] = month.split('-')
            const date = new Date(year, monthNumber, 0)

            // 获取指定月份的天数
            return date.getDate()
        },

        
        getAgentNotice() {
            this.$request.get('/get_contact_platform').then((res) => {
                console.log('getAgentNotice',res)
                this.authentication = res
            })
        },
    },
}
</script>

<style scoped>
.flexCCC {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
</style>